package com.ccsoft.netty.heartbeat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author chanchaw
 * @create 2022-07-20 14:33
 */
public class HeartbeatClient {
    private String server = "localhost";
    private int port = 2222;
    private Bootstrap bootstrap;
    private Channel channel;

    private RetryPolicy retryPolicy;

    public HeartbeatClient(String server, int port) {
        this.server = server;
        this.port = port;
        init();
    }

    private void init(){
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ClientInitializer(HeartbeatClient.this));
    }

    protected void connect(){
        synchronized (bootstrap){
            ChannelFuture channelFuture = bootstrap.connect(server, port);
            channelFuture.addListener(getConnectionListener());
            this.channel = channelFuture.channel();
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()) System.out.println("客户端已连接到服务端！");
                    else System.out.println("连接服务端失败！");
                }
            });
        }
    }

    public RetryPolicy getRetryPolicy() {
        return retryPolicy;
    }

    public void setRetryPolicy(RetryPolicy retryPolicy) {
        this.retryPolicy = retryPolicy;
    }

    private ChannelFutureListener getConnectionListener() {
        return new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    future.channel().pipeline().fireChannelInactive();
                }
            }
        };
    }

    public static void main(String[] args) {
        HeartbeatClient client = new HeartbeatClient("localhost",2222);
        client.setRetryPolicy(new ExponentialBackOffRetry(1000,3,10000));
        client.connect();
    }
}
